package com.codefish.controller;

import com.codefish.entity.BaseFamily;
import com.codefish.entity.SysUserTokenEntity;
import com.codefish.service.BaseFamilyService;
import com.codefish.util.Assert;
import com.codefish.util.JWTService;
import com.codefish.util.R;
import lombok.extern.slf4j.XSlf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;


/**
 * 家庭
 *
 * @author codefish
 * @email cool_fish@aliyun.com
 * @date 2021-07-06 19:33:54
 */
@RestController
@RequestMapping("/baseFamily")
public class BaseFamilyController {


    /**
     * 家庭
     */
    @Autowired
    private BaseFamilyService baseFamilyService;


    /**
     * 添加单个
     *
     * @param family
     * @return
     */
    @PostMapping("/saveOne")
    public R saveOne(@RequestHeader("Authentication") String token, @RequestBody BaseFamily family) {

        Assert.isNull(token, "token不可为空");
        Assert.isNull(family.getFamilyName(), "familyName不可为空");

        SysUserTokenEntity user = JWTService.getUser(token);
        if (ObjectUtils.isEmpty(user) || ObjectUtils.isEmpty(user.getId())) {
            return R.error("无效token");
        }

        family.setCreateId(user.getId());
        boolean saveFlag = baseFamilyService.saveOne(family);
        if (!saveFlag) {
            return R.error("新增失败");
        }

        return R.ok();
    }

    /**
     * 修改单个
     * @param token
     * @param family
     * @return
     */
    @PostMapping("/updateOne")
    public R updateOne(@RequestHeader("Authentication") String token
            , @RequestBody BaseFamily family) {

        Assert.isNull(family.getId(),"id不可为空");
        Assert.isNull(token, "token不可为空");
        Assert.isNull(family.getFamilyName(), "familyName不可为空");

        SysUserTokenEntity user = JWTService.getUser(token);
        if (ObjectUtils.isEmpty(user) || ObjectUtils.isEmpty(user.getId())) {
            return R.error("无效token");
        }
        boolean flag = baseFamilyService.updateOne(family);

        if (!flag){
            return R.error("修改失败");
        }

        return R.ok("修改成功");
    }

}
